<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Model\Interlocution;
use App\Model\User;
use App\Http\Controllers\Controller;
use Session;

class InterlocutionController extends Controller
{
    public function __construct()
    {
        $this->middleware('RejectNobody');
    }

    public function Index(Request $request)
    {
        $id = Session::get('id', '0');
        if ($id == '0') {
            return response()->view('errors.503', [], 404);
        }
        $for = $request->get('for');
        $data = Interlocution::Get_List($id, $for);
        $str = null;
        $num = count($data);
        for ($i = $num - 1; $i >= 0; --$i) {
            if ($data[$i]->uid == $id) {
                $str .= '<li class="text-right">
						<time class="text-muted">'.$data[$i]->created_at.'</time>
						<div>
							<strong class="pull-right text-primary">&nbsp&nbsp<i class="fa fa-angle-left"></i>&nbspself</strong>
							<div>'.htmlspecialchars($data[$i]->body).'</div>
						</div>
					</li>';
            } else {
                $str .= '<li class="text-left">
						<time class="text-muted">'.$data[$i]->created_at.'</time>
						<div>
							<strong class="pull-left text-primary">towers&nbsp<i class="fa fa-angle-right"></i>&nbsp&nbsp</strong>
							<div>'.htmlspecialchars($data[$i]->body).'</div>
						</div>
					</li>';
            }
        }
        Interlocution::Clear_Msg($for, $id);
        if ($request->ajax()) {
            return response()->json(['str' => $str]);
        } else {
            return view('user.Interlocution', ['str' => $str]);
        }
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'body' => 'required',
        ]);
        $data['uid'] = Session::get('id', '0');
        $data['body'] = $request->input('body');
        $data['for'] = $request->get('for');
        $data['status'] = 1;
        Interlocution::Add($data);

        return response()->json(['status' => '1', 'info' => '留言成功']);
    }
}
